package com.newegg.datafeed.adserving.api;

import java.io.File;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.newegg.datafeed.adserving.api.annotation.AccessRequired;
import com.newegg.datafeed.adserving.model.UserType;
import com.newegg.datafeed.adserving.response.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags="文件上传")
@RestController
@RequestMapping("/api/upload")
public class UploadAPI extends BaseAPI{
	
	@Value("${local.file.path}")
	private String path;
	
	@ApiOperation(value="保存上传之后的图片到数据库", produces="application/json")
    @RequestMapping(value="/", method = RequestMethod.POST)
	@ResponseBody
	@AccessRequired(role={UserType.USER})
    public Response<String> upload(@RequestPart MultipartFile file) throws Exception {
		String filename = UUID.randomUUID() + "." + file.getOriginalFilename();
		File fileSourcePath = new File(path);
		File fileSource = new File(fileSourcePath, UUID.randomUUID() + "." + file.getOriginalFilename());
		if (!fileSourcePath.exists()) {
		    fileSourcePath.mkdirs();
		}
		file.transferTo(fileSource);
		return SUCCESS(filename);
    }
}
